//
//  GYBleDataManager.m
//  LockManagement
//
//  Created by 丁燕春 on 2018/8/2.
//  Copyright © 2018年 yunjiazhineng. All rights reserved.
//


/** 跟秘钥 */
static NSString *ROOT_SECRET_KEY = @"SDtt6789"; //53447474 36373839

/** 第一种初始胡秘钥 */
static NSString *INIT_SECRET_KEY = @"TTMJ_234"; //54544d4a 5f323334

/** 第二种初始秘钥 */
static NSString *INITSECOND_SECRET_KEY = @"TTMJ_345"; //54544d4a 5f333435

#import "GYBleDataManager.h"
//引入IOS自带密码库
#import <CommonCrypto/CommonCryptor.h>
#import "GYUserInfo.h"
#import "NSData+LBXCrypt.h"
#import "GYDateTools.h"
#import "GYDateTools.h"

@implementation GYBleDataManager

+ (NSNumber *)convertDataToHexStr:(NSData *)data
{
    if (!data || [data length] == 0) {
        return 0;
    }
    NSMutableString *string = [[NSMutableString alloc] initWithCapacity:[data length]];
    
    [data enumerateByteRangesUsingBlock:^(const void *bytes, NSRange byteRange, BOOL *stop) {
        unsigned char *dataBytes = (unsigned char*)bytes;
        for (NSInteger i = 0; i < byteRange.length; i++) {
            NSString *hexStr = [NSString stringWithFormat:@"%x", (dataBytes[i]) & 0xff];
            if ([hexStr length] == 2) {
                [string appendString:hexStr];
            } else {
                [string appendFormat:@"0%@", hexStr];
            }
        }
    }];
    return [self numberHexString:string];
}


+ (NSMutableData *)convertHexStrToData:(NSString *)str {
    
    if (!str || [str length] == 0) {
        
        return nil;
    }
    NSMutableData *hexData = [[NSMutableData alloc] initWithCapacity:8];
    
    NSRange range;
    
    if ([str length] %2 == 0) {
        range = NSMakeRange(0,2);
    } else {
        range = NSMakeRange(0,1);
    }
    for (NSInteger i = range.location; i < [str length]; i += 2) {
        
        unsigned int anInt;
        
        NSString *hexCharStr = [str substringWithRange:range];
        
        NSScanner *scanner = [[NSScanner alloc] initWithString:hexCharStr];
    
        [scanner scanHexInt:&anInt];
        
        NSData *entity = [[NSData alloc] initWithBytes:&anInt length:1];
        
        [hexData appendData:entity];
        
        range.location += range.length;
        
        range.length = 2;
        
    }
    return hexData;
    
}

// 16进制转10进制

+ (NSNumber *) numberHexString:(NSString *)aHexString

{
    // 为空,直接返回.
    
    if (nil == aHexString)
        
    {
        
        return 0;
        
    }
    
    NSScanner * scanner = [NSScanner scannerWithString:aHexString];
    
    unsigned long long longlongValue;
    
    [scanner scanHexLongLong:&longlongValue];
    
    
    
    //将整数转换为NSNumber,存储到数组中,并返回.
    
    NSNumber * hexNumber = [NSNumber numberWithLongLong:longlongValue];
    
    
    
    return hexNumber;
}

//10进制转16进制
+(NSString *)ToHex:(long long int)tmpid
{
    NSString *nLetterValue;
    NSString *str =@"";
    long long int ttmpig;
    for (int i =0; i<9; i++) {
        ttmpig=tmpid%16;
        tmpid=tmpid/16;
        switch (ttmpig)
        {
            case 10:
                nLetterValue =@"A";break;
            case 11:
                nLetterValue =@"B";break;
            case 12:
                nLetterValue =@"C";break;
            case 13:
                nLetterValue =@"D";break;
            case 14:
                nLetterValue =@"E";break;
            case 15:
                nLetterValue =@"F";break;
            default:nLetterValue=[[NSString alloc]initWithFormat:@"%lli",ttmpig];
                
        }
        str = [nLetterValue stringByAppendingString:str];
        if (tmpid == 0) {
            break;
        }
        
    }
    return str;
}


// 十六进制转换为普通字符串的。
+ (NSString *)stringFromHexString:(NSString *)hexString { //
    
    char *myBuffer = (char *)malloc((int)[hexString length] / 2 + 1);
    bzero(myBuffer, [hexString length] / 2 + 1);
    for (int i = 0; i < [hexString length] - 1; i += 2) {
        unsigned int anInt;
        NSString * hexCharStr = [hexString substringWithRange:NSMakeRange(i, 2)];
        NSScanner * scanner = [[NSScanner alloc] initWithString:hexCharStr];
        [scanner scanHexInt:&anInt];
        myBuffer[i / 2] = (char)anInt;
    }
    NSString *unicodeString = [NSString stringWithCString:myBuffer encoding:4];
    NSLog(@"------字符串=======%@",unicodeString);
    return unicodeString;
    
    
}


//普通字符串转换为十六进制的。

+ (NSString *)hexStringFromString:(NSString *)string{
    NSData *myD = [string dataUsingEncoding:NSUTF8StringEncoding];
    Byte *bytes = (Byte *)[myD bytes];
    //下面是Byte 转换为16进制。
    NSString *hexStr=@"";
    for(int i=0;i<[myD length];i++)
        
    {
        NSString *newHexStr = [NSString stringWithFormat:@"%x",bytes[i]&0xff];///16进制数
        
        if([newHexStr length]==1)
            
            hexStr = [NSString stringWithFormat:@"%@0%@",hexStr,newHexStr];
        
        else
            
            hexStr = [NSString stringWithFormat:@"%@%@",hexStr,newHexStr];
    }
    return hexStr;
}


/**
 字节数组转化16进制数
 */
+(NSString *) parseByteArray2HexString:(Byte[]) bytes count:(int)count
{
    NSMutableString *hexStr = [[NSMutableString alloc]init];
    if(bytes)
    {
        for (int i=0;i< count;i++)
        {
            NSString *hexByte = [NSString stringWithFormat:@"%x",bytes[i] & 0xff];///16进制数
            
            if([hexByte length]==1)
                [hexStr appendFormat:@"0%@", hexByte];
            else
                [hexStr appendFormat:@"%@", hexByte];
        }
    }
    
    return [hexStr uppercaseString];
}

#pragma mark -- 数据发送方法

//得到蓝牙钥匙电量
+ (NSData *)getKeyElc {
    Byte byte[] = {0xfa, 0xfb, 0x06, 0x00,
        0x02,0xff,0xf7};
    NSData *data = [NSData dataWithBytes:byte length:7];
    
    NSLog(@"getKeyElc========%@",data);
    
    return data;
}

//得到mac地址
+ (NSData *)getkeyMacAddress {
    Byte headByte[] = {0xfa,0xfb,0x0d,0x00,0x02,0xff,0xf0};
    NSData *data = [NSData dataWithBytes:headByte length:7];
    
    NSLog(@"getkeyMacAddress==========%@",data);
    return data;
}

//读取门锁的信息
+ (NSData *)getLockInfomation {
    NSMutableData *allData = [NSMutableData data];
    //头部
    Byte byte[] = {0xfa, 0xfb, 0x01,0x00,0x0a};
    NSData *headData = [NSData dataWithBytes:byte length:5];
    [allData appendData:headData];
    
    //内容
    Byte byte1[] = {0xff};
    NSData *contentData = [NSData dataWithBytes:byte1 length:1];
    NSData *encryData = [contentData LBXCryptWithOp:LBXOperaton_Encrypt algorithm:LBXAlgorithm_DES optionMode:LBXOptionMode_ECB padding:LBXPaddingMode_Zero key:ROOT_SECRET_KEY iv:nil error:nil];
    [allData appendData:encryData];
    
    Byte foot[] = {0xfd,0x1c};
    NSData *footData = [NSData dataWithBytes:foot length:2];
    [allData appendData:footData];
    
    NSLog(@"getLockInfomation====================%@",allData);
    return allData;
}

//初始化门锁
+ (NSData *)setupLock {
    
    NSMutableData *allData = [NSMutableData data];
    
    Byte head[] = {0xfa,0xfb,0x02};
    NSData *headData = [NSData dataWithBytes:head length:3];
    [allData appendData:headData];
    
    NSMutableData *contentData = [NSMutableData data];
    //初始化秘钥
    Byte keys[] = {0x54,0x54,0x4d,0x4a,0x5f,0x32,0x33,0x34};//TTMJ_234
    NSData *keysData = [NSData dataWithBytes:keys length:8];
    [contentData appendData:keysData];
    
    //配置参数
    Byte con[] = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
    NSData *conData = [NSData dataWithBytes:con length:8];
    [contentData appendData:conData];
    
    Byte lock[] = {0x01,0x03,0x05,0x05,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff};
    NSData *lockData = [NSData dataWithBytes:&lock length:16];
    [contentData appendData:lockData];
    NSLog(@"setupLockData==加密签=============%@",contentData);
    //把内容加密
    NSData *encryData = [contentData LBXCryptWithOp:LBXOperaton_Encrypt algorithm:LBXAlgorithm_DES optionMode:LBXOptionMode_ECB padding:LBXPaddingMode_Zero key:ROOT_SECRET_KEY iv:nil error:nil];
    
    
    //首先补充头部的2个字节 在添加内容
    //计算内容的长度
    unsigned short count = encryData.length+2;
    //NSLog(@"length===============%d",count);
    Byte low = count & 0XFF;//WORD_HI(count);
    count >>=8; //像右移 8未
    
    Byte lengtn[2];
    lengtn[0] = count;
    lengtn[1] = low;
    
    NSData *lengtnData = [NSData dataWithBytes:lengtn length:2];
    [allData appendData:lengtnData];
    
    
    [allData appendData:encryData];
    
    //Byte foot[] = {0xf8,0x6f};
    NSData *footData = [self generateCRC:encryData param:2+2+encryData.length];//[NSData dataWithBytes:foot length:2];
    [allData appendData:footData];
    
    
//    Byte ceshi[] = {0xfa,0xfb,0x02,0x00,0x22,0x54,0x54,0x4d,0x4a,0x5f,0x32,0x33,0x34,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x01,0x03,0x05,0x05,0xfd,0xa2};
//    NSData *ceshiData = [NSData dataWithBytes:&ceshi length:39];
    
    NSLog(@"setupLock===========%@",allData);
    return allData;
}

//开门
+ (NSData *)openOrCloseTheDoor:(NSString *)lockID schoolBeginTime:(NSString *)beignTime schoolEndTime:(NSString *)endTime schoolTime:(NSString *)schoolTime operationType:(int)type SecretKey:(id)screctkey{
    
    NSMutableData *allData = [NSMutableData data];

    //头部
    Byte head[] = {0xfa,0xfb,0x03};
    NSData *headData = [NSData dataWithBytes:head length:3];
    [allData appendData:headData];

    //内容
    NSMutableData *contentData = [NSMutableData data];

    //获取加密前钥匙串
    NSMutableData *keyData = [NSMutableData data];
    //用户编号4
    int userID = [GYUserInfo loadUserInfo].userID;
    NSData *userData = [NSData dataWithBytes:&userID length:4];
    [keyData appendData:userData];

    //锁具编号16
    NSArray *lockNums = [lockID componentsSeparatedByString:@"-"];
    Byte lock[] = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
    NSMutableData *lockData = [NSMutableData dataWithBytes:lock length:16];
    NSString *lockString = @"";
    for (int i = 0; i < lockNums.count; i++) {
        unsigned short count = [lockNums[i] intValue];
        //NSLog(@"length===============%d",count);
        Byte low = count & 0XFF;//WORD_HI(count);
        count >>=8; //像右移 8未

        Byte lengtn[2];
        lengtn[0] = count;
        lengtn[1] = low;
        NSData *lengthData = [NSData dataWithBytes:lengtn length:2];
        [lockData replaceBytesInRange:NSMakeRange(i * 2, 2) withBytes:lengthData.bytes];
    }
    [keyData appendData:lockData];
    //NSLog(@"lockData=============%@",lockData);

    //授权开始开始时间 (首先把时间转成一个字符串)14
    NSString *originalStyle = @"yyyy-MM-dd HH:mm:ss";
    NSString *nowStyle = @"yyyyMMddHHmmss";
    
    
    NSString *begin = [GYDateTools changeTimeFormat:beignTime withOriginalStyle:originalStyle withNowStyle:nowStyle];
    NSData *beginData = [begin dataUsingEncoding:NSUTF8StringEncoding];
    //NSLog(@"beginData============%@   =========%@",[[NSString alloc] initWithData:beginData encoding:NSUTF8StringEncoding],beginData);
    [keyData appendData:beginData];

    //授权结束时间14
    NSString *end = [GYDateTools changeTimeFormat:endTime withOriginalStyle:originalStyle withNowStyle:nowStyle];
    NSData *endData = [end dataUsingEncoding:NSUTF8StringEncoding];
    //NSLog(@"endData============%@    =========%@",[[NSString alloc] initWithData:endData encoding:NSUTF8StringEncoding],endData);
    [keyData appendData:endData];

    //授权时间14
    NSString *school = [GYDateTools changeTimeFormat:schoolTime withOriginalStyle:originalStyle withNowStyle:nowStyle];
    NSData *schoolData = [school dataUsingEncoding:NSUTF8StringEncoding];
    //NSLog(@"schoolData============%@    =========%@",[[NSString alloc] initWithData:schoolData encoding:NSUTF8StringEncoding],schoolData);
    [keyData appendData:schoolData];

    //钥匙串尾部2
    Byte keyFoot[] = {0x00,0x00};
    NSData *keyFootData = [NSData dataWithBytes:keyFoot length:2];
    [keyData appendData:keyFootData];

    //然后钥匙串加密 64
    //NSLog(@"钥匙串加密之前的结果=========%@   =========%lu",keyData,(unsigned long)keyData.length);
    NSData *encrtyKeyData = [keyData LBXCryptWithOp:LBXOperaton_Encrypt algorithm:LBXAlgorithm_DES optionMode:LBXOptionMode_ECB padding:LBXPaddingMode_NONE key:INIT_SECRET_KEY iv:nil error:nil];
    //NSLog(@"钥匙串加密之后的结果---------%@  =========%lu",encrtyKeyData,(unsigned long)encrtyKeyData.length);
    [contentData appendData:encrtyKeyData];

    //最后完成的内容是
    [contentData appendData:userData];

    //操作内容是
    NSData *operationData = [NSData dataWithBytes:&type length:1];
    [contentData appendData:operationData];

    //NSLog(@"内容加密之前------%lu",(unsigned long)contentData.length);
    //在使用通讯秘钥加密内容
    NSData *encrtyData = [contentData LBXCryptWithOp:LBXOperaton_Encrypt algorithm:LBXAlgorithm_DES optionMode:LBXOptionMode_ECB padding:LBXPaddingMode_Zero key:screctkey iv:nil error:nil];
    //NSLog(@"内容加密之后----===%lu",(unsigned long)encrtyData.length);

    //首先补充头部的2个字节 在添加内容
    //计算内容的长度
    unsigned short count = encrtyData.length+2;
    //NSLog(@"length===============%d",count);
    Byte low = count & 0XFF;//WORD_HI(count);
    count >>=8; //像右移 8未

    Byte lengtn[2];
    lengtn[0] = count;
    lengtn[1] = low;

    NSData *lengtnData = [NSData dataWithBytes:lengtn length:2];
    [allData appendData:lengtnData];


    [allData appendData:encrtyData];

#warning 测试
    //尾部
    NSData *footData = [self generateCRC:encrtyData param:3+2+encrtyData.length];
    [allData appendData:footData];
    
    NSLog(@"openTheDoor======%@",allData);
    return allData;
}

//授权钥匙
+ (NSData *)autoKey:(NSData *)lockData schoolBeginTime:(NSString *)beignTime schoolEndTime:(NSString *)endTime schoolTime:(NSString *)schoolTime operationType:(int)type mac:(NSString *)macHexString {
    
    NSMutableData *allData = [NSMutableData data];
    
    Byte head[] = {0xfa,0xfb,0x05};
    NSData *headData = [NSData dataWithBytes:head length:3];
    [allData appendData:headData];
    
    //内容
    NSMutableData *contentData = [NSMutableData data];
    
    //获取加密前钥匙串
    NSMutableData *keyData = [NSMutableData data];
    //用户编号4
    //Byte user[] = {0x01,0x01,0x01,0x01};
    int userID = [GYUserInfo loadUserInfo].userID;
    NSData *userData = [NSData dataWithBytes:&userID length:4];
    [keyData appendData:userData];
    
    //锁具编号16
//    NSArray *lockNums = [lockID componentsSeparatedByString:@"-"];
//    Byte lock[] = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
//    NSMutableData *lockData = [NSMutableData dataWithBytes:lock length:16];
//    NSString *lockString = @"";
//    for (int i = 0; i < lockNums.count; i++) {
//        unsigned short count = [lockNums[i] intValue];
//        //NSLog(@"length===============%d",count);
//        Byte low = count & 0XFF;//WORD_HI(count);
//        count >>=8; //像右移 8未
//        
//        Byte lengtn[2];
//        lengtn[0] = count;
//        lengtn[1] = low;
//        NSData *lengthData = [NSData dataWithBytes:lengtn length:2];
//        [lockData replaceBytesInRange:NSMakeRange(i * 2, 2) withBytes:lengthData.bytes];
//    }
    [keyData appendData:lockData];
    //NSLog(@"lockData=============%@",lockData);
    
    //授权开始开始时间 (首先把时间转成一个字符串)14
    NSString *originalStyle = @"yyyy-MM-dd HH:mm:ss";
    NSString *nowStyle = @"yyyyMMddHHmmss";
    
    
    NSString *begin = [GYDateTools changeTimeFormat:beignTime withOriginalStyle:originalStyle withNowStyle:nowStyle];
    NSData *beginData = [begin dataUsingEncoding:NSUTF8StringEncoding];
    //NSLog(@"beginData============%@   =========%@",[[NSString alloc] initWithData:beginData encoding:NSUTF8StringEncoding],beginData);
    [keyData appendData:beginData];
    
    //授权结束时间14
    NSString *end = [GYDateTools changeTimeFormat:endTime withOriginalStyle:originalStyle withNowStyle:nowStyle];
    NSData *endData = [end dataUsingEncoding:NSUTF8StringEncoding];
    //NSLog(@"endData============%@    =========%@",[[NSString alloc] initWithData:endData encoding:NSUTF8StringEncoding],endData);
    [keyData appendData:endData];
    
    //授权时间14
    NSString *school = [GYDateTools changeTimeFormat:schoolTime withOriginalStyle:originalStyle withNowStyle:nowStyle];
    NSData *schoolData = [school dataUsingEncoding:NSUTF8StringEncoding];
    //NSLog(@"schoolData============%@    =========%@",[[NSString alloc] initWithData:schoolData encoding:NSUTF8StringEncoding],schoolData);
    [keyData appendData:schoolData];
    
    //钥匙串尾部2
    Byte keyFoot[] = {0x00,0x00};
    NSData *keyFootData = [NSData dataWithBytes:keyFoot length:2];
    [keyData appendData:keyFootData];
    
    //然后钥匙串加密 64
    //NSLog(@"钥匙串加密之前的结果=========%@   =========%lu",keyData,(unsigned long)keyData.length);
    NSData *encrtyKeyData = [keyData LBXCryptWithOp:LBXOperaton_Encrypt algorithm:LBXAlgorithm_DES optionMode:LBXOptionMode_ECB padding:LBXPaddingMode_NONE key:INIT_SECRET_KEY iv:nil error:nil];
    //NSLog(@"钥匙串加密之后的结果---------%@  =========%lu",encrtyKeyData,(unsigned long)encrtyKeyData.length);
    [contentData appendData:encrtyKeyData];
    
    //添加其他的内容
    //1.用户编号
    [contentData appendData:userData];
    
    //2.添加操作内行
    NSData *operationData = [NSData dataWithBytes:&type length:1];
    [contentData appendData:operationData];
    
    //3.添加锁具识别号
    [contentData appendData:lockData];
    
    //4.蓝牙mac地址
    //Byte keymac[] = {0xef,0x74,0x4a,0xe6,0x13,0xae};
    NSData *macData = [GYBleDataManager convertHexStrToData:macHexString];
    //NSLog(@"蓝牙的mac地址============%@",macData);
    [contentData appendData:macData];
    
    //还有两位不知道是什么
    Byte *unknow[] = {0x00};
    NSData *unknowData = [NSData dataWithBytes:unknow length:1];
    [contentData appendData:unknowData];

    //要再添加一次
    [contentData appendData:unknowData];
    
    
    //5.储存位置
    Byte caches[] = {0x10};
    NSData *cachesData = [NSData dataWithBytes:caches length:1];
    [contentData appendData:cachesData];
    
    //有效时间
    Byte effective[] = {0x00,0x0a};
    NSData *effectiveData = [NSData dataWithBytes:effective length:2];
    [contentData appendData:effectiveData];
    
    //有效次数
    Byte effTime[] = {0x0a};
    NSData *effTimeData = [NSData dataWithBytes:effTime length:1];
    [contentData appendData:effTimeData];
    
    //加密内容
    //NSLog(@"加密内容前==================%@         =======%lu",contentData,(unsigned long)contentData.length);
    NSData *encrtyData = [contentData LBXCryptWithOp:LBXOperaton_Encrypt algorithm:LBXAlgorithm_DES optionMode:LBXOptionMode_ECB padding:LBXPaddingMode_Zero key:INITSECOND_SECRET_KEY iv:nil error:nil];
    //NSLog(@"加密内容后==================%@       =======%lu",encrtyData,(unsigned long)encrtyData.length);
    
    //首先补充头部的2个字节 在添加内容
    //计算内容的长度
    unsigned short count = encrtyData.length+2;
    //NSLog(@"length===============%d",count);
    Byte low = count & 0XFF;//WORD_HI(count);
    count >>=8; //像右移 8未
    
    Byte lengtn[2];
    lengtn[0] = count;
    lengtn[1] = low;
    
    NSData *lengtnData = [NSData dataWithBytes:lengtn length:2];
    [allData appendData:lengtnData];
    
    
    [allData appendData:encrtyData];
    
    //尾部
    NSData *footData = [self generateCRC:encrtyData param:5+2+encrtyData.length];
    [allData appendData:footData];
    
    NSLog(@"autoKey===========%@",allData);
    return allData;
}

//绑定钥匙
+ (NSData *)bindBleKey {
    //S + T + L
    NSMutableData *allData = [NSMutableData data];

    Byte byte[] = {0xfa,0xfb,0x07,0x00,0x12};
    NSData *headData = [NSData dataWithBytes:byte length:5];
    [allData appendData:headData];


    //内容
    NSMutableData *contentData = [NSMutableData data];

    //用户编号
    int userID = [GYUserInfo loadUserInfo].userID;
    //Byte user[] = {0x01,0x01,0x01,0x01};
    NSData *userData = [NSData dataWithBytes:&userID length:4];
    [contentData appendData:userData];

    //初始化秘钥
    Byte keys[] = {0x54,0x54,0x4d,0x4a,0x5f,0x33,0x34,0x35};
    NSData *keysData = [NSData dataWithBytes:keys length:8];
    [contentData appendData:keysData];
    //NSLog(@"contentData========%@",contentData);
    //把内容加密
    NSData *encryData = [contentData LBXCryptWithOp:LBXOperaton_Encrypt algorithm:LBXAlgorithm_DES optionMode:LBXOptionMode_ECB padding:LBXPaddingMode_Zero key:ROOT_SECRET_KEY iv:nil error:nil];
    //NSLog(@"encryData========%@",encryData);
    [allData appendData:encryData];
#warning 正确 的 然后修改 在测试 [self parseByteArray2HexString:(Byte *)encryData.bytes count:(int)encryData.length]
    NSData *footData = [self generateCRC:encryData param:25];

    [allData appendData:footData];

    NSLog(@"bindBleKey===========%@",allData);
    return allData;
}

//查询锁具详情信息
+ (NSData *)getLockDetailesInfomations {
    Byte ceshi[] = {0xfa,0xfb,0x08,0x00,0x03,0xff,0xfe,0xf5};
    NSData *ceshiData = [NSData dataWithBytes:ceshi length:8];
    
    return ceshiData;
}

//给锁校时
+ (NSData *)schoolTimeToLock {
    NSMutableData *allData = [NSMutableData data];
    
    Byte head[] = {0xfa,0xfb,0x0c,0x00,0x12};
    NSData *headData = [NSData dataWithBytes:head length:5];
    
    //内容  这个加密的秘钥需要 协商通讯秘钥---> 产生秘钥之后才可以
    Byte conten[] = {0x32,0x30,0x31,0x38,0x30,37,0x32,0x39,0x31,0x34,0x31,0x34,0x35,0x33};
    NSData *contentData = [NSData dataWithBytes:conten length:14];
    NSLog(@"contentData=============%@",[[NSString alloc] initWithData:contentData encoding:NSUTF8StringEncoding]);
    
    NSLog(@"schoolTimeToLock======%@",allData);
    return allData;
}

//重置秘钥
+ (NSData *)resetSecretKey {
    NSMutableData *allData = [NSMutableData data];
    
    Byte head[] = {0xfa,0xfb,0x0b,0x00,0x12};
    NSData *data = [NSData dataWithBytes:head length:5];
    [allData appendData:data];
    
    NSLog(@"resetSecretKey======%@",allData);
    return allData;
}

//修改锁识别号
+ (NSData *)modfyLockNumber {
    NSMutableData *allData = [NSMutableData data];
    
    Byte head[] = {0xfa,0xfb,0x0b,0x00,0x12};
    NSData *data = [NSData dataWithBytes:head length:5];
    [allData appendData:data];
    
    
    
    
    NSLog(@"modfyLockNumber======%@",allData);
    return allData;
}

//给钥匙校时
+ (NSData *)schoolTimeToKey {
    NSMutableData *allData = [NSMutableData data];

    Byte head[] = {0xfa,0xfb,0x0c};
    NSData *headData = [NSData dataWithBytes:head length:3];
    [allData appendData:headData];

    //内容
    NSString *timeString = @"20170101010101";
    //NSString *currentTime = [GYDateTools returnCurrentDateToString:@"yyyyMMddHHmmss"];

    NSData *contentData = [timeString dataUsingEncoding:NSUTF8StringEncoding];
    //测试
//    Byte content[] = {0x32,0x30,0x31,0x38,0x30,0x37,0x32,0x39,0x31,0x34,0x31,0x34,0x35,0x33};
//    NSData *contentData = [NSData dataWithBytes:content length:14];
    NSLog(@"contentData============%@",contentData);
    NSData *encryData = [contentData LBXCryptWithOp:LBXOperaton_Encrypt algorithm:LBXAlgorithm_DES optionMode:LBXOptionMode_ECB padding:LBXPaddingMode_Zero key:INITSECOND_SECRET_KEY iv:nil error:nil];

    //计算内容的长度
    unsigned short count = encryData.length+2;
    //NSLog(@"length===============%d",count);
    Byte low = count & 0XFF;//WORD_HI(count);
    count >>=8; //像右移 8未

    Byte lengtn[2];
    lengtn[0] = count;
    lengtn[1] = low;

    NSData *lengtnData = [NSData dataWithBytes:lengtn length:2];
    [allData appendData:lengtnData];

    [allData appendData:encryData];
#warning 正确然后修改  测试 [GYBleDataManager parseByteArray2HexString:(Byte *)encryData.bytes count:(int)encryData.length]
    NSData *footData = [GYBleDataManager generateCRC:encryData param:encryData.length+2+12];//T(指令)+L(数据内容+校验位字节数)+v(内容)
    [allData appendData:footData];
    //unsigned short 两个字节表示16进制数据
    
//    Byte ceshi[] = {0xfa,0xfb,0x0c,0x00,0x12,0x25,0x0c,0x9a,0x58,0xfe,0x4e,0x91,0xb8,0x63,0xf2,0x49,0x09,0xf9,0xf1,0xb0,0x56,0xf7,0x92};
//    NSData *ceshiData = [NSData dataWithBytes:ceshi length:23];
//    NSLog(@"ceshiData=============%@",ceshiData);
    
    NSLog(@"schoolTimeToKey=======%@",allData);
    return allData;
}


//协商通讯秘钥
+ (NSData *)consultKey {
    NSMutableData *allData = [NSMutableData data];

    Byte head[] = {0xfa,0xfb,0x14};
    NSData *headData = [NSData dataWithBytes:head length:3];
    [allData appendData:headData];

    //内容
    Byte conten[] = {0X01,0x01,0x01,0x01,0x01,0x01,0x01,0x01};
    NSData *contentData = [NSData dataWithBytes:conten length:8];
    //NSLog(@"contentData========%@",contentData);
    
    NSData *encryData = [contentData LBXCryptWithOp:LBXOperaton_Encrypt algorithm:LBXAlgorithm_DES optionMode:LBXOptionMode_ECB padding:LBXPaddingMode_NONE key:INIT_SECRET_KEY iv:nil error:nil];
    //NSLog(@"encryData========%@",encryData);
    
    //计算内容的长度
    unsigned short count = encryData.length+2;
    //NSLog(@"length===============%d",count);
    Byte low = count & 0XFF;//WORD_HI(count);
    count >>=8; //像右移 8未
    
    Byte lengtn[2];
    lengtn[0] = count;
    lengtn[1] = low;
    
    NSData *lengtnData = [NSData dataWithBytes:lengtn length:2];
    [allData appendData:lengtnData];
    
    
    [allData appendData:encryData];
#warning 正确  然后修改  [self parseByteArray2HexString:(Byte *)encryData.bytes count:encryData.length]
    NSData *footData = [self generateCRC:encryData param:30];
    [allData appendData:footData];

    NSLog(@"consultKey======%@",allData);
    
//    Byte ceshi[] = {0xfa,0xfb,0x14,0x00,0x0a,0x09,0xea,0xbe,0x0b,0xfb,0xee,0xdd,0x24,0xfb,0x3b};
//    NSData *ceshiData = [NSData dataWithBytes:ceshi length:15];
//    NSLog(@"ceshiData=============%@",ceshiData);
    return allData;
}

+ (NSData *)consultKeySecond:(int)type content:(NSData *)contentData secret_key:(id)secret_key {
    NSMutableData *allData = [NSMutableData data];
    
    Byte head[] = {0xfa,0xfb};
    NSData *headData = [NSData dataWithBytes:head length:2];
    [allData appendData:headData];
    
    NSData *titleData = [NSData dataWithBytes:&type length:1];
    [allData appendData:titleData];
    
    //计算内容
    NSData *yihuoData;
    if (type == 22) {
        yihuoData = contentData; //最后的时候不用异或
    }else {
        yihuoData = [self yihuo0X5A:[contentData mutableCopy]];
    }
    NSLog(@"+++++++++++++++++++%@",contentData);
    
    NSData *encryData = [yihuoData LBXCryptWithOp:LBXOperaton_Encrypt algorithm:LBXAlgorithm_DES optionMode:LBXOptionMode_ECB padding:LBXPaddingMode_NONE key:secret_key iv:nil error:nil];
    
    //计算内容的长度
    unsigned short count = encryData.length+2;
    //NSLog(@"length===============%d",count);
    Byte low = count & 0XFF;//WORD_HI(count);
    count >>=8; //像右移 8未
    
    Byte lengtn[2];
    lengtn[0] = count;
    lengtn[1] = low;
    
    NSData *lengtnData = [NSData dataWithBytes:lengtn length:2];
    [allData appendData:lengtnData];
    
    //添加内容
    [allData appendData:encryData];
    
#warning 正确  然后修改-- [self parseByteArray2HexString:(Byte *)encryData.bytes count:encryData.length]
    NSData *footData = [self generateCRC:encryData param:10+type];
    [allData appendData:footData];

    NSLog(@"consultKeySecond==========%@",allData);
    
    return allData;
}

//锁日志上传指令
+ (NSData *)uploadLockLog {
    NSMutableData *allData = [NSMutableData data];
    
    Byte head[] = {0xfa,0xfb,0x0e,0x00,0x02};
    NSData *headData = [NSData dataWithBytes:head length:5];
    [allData appendData:headData];
    
    
    NSData *footData = [self generateCRC:[[NSData alloc] init] param:16];
    [allData appendData:footData];
    
    NSLog(@"uploadLockLog======%@",allData);
    return allData;
}

//和0x5A异或后的值
+ (NSData*)yihuo0X5A:(NSMutableData*)dataresult

{
    
    Byte*byte1 = (unsigned char*)[dataresult bytes];
    
    Byte sum =0x5A;
    
    for(int i =0 ; i<dataresult.length; i++)
    {
        
        byte1[i]^=sum;
        
    }
    
    NSData*data1 = [[NSData alloc]initWithBytes:byte1 length:dataresult.length];
    
    NSString *string = [[NSString alloc]initWithBytes:byte1 length:dataresult.length encoding:NSUTF8StringEncoding];
    
    return data1;
}


+ (NSData *)generateCRC:(NSData *)data param:(int)param{
    //NSLog(@"str=========%@",str);
    //把16进制字符串转换成字节数组
//    long len = ([str length]/2);
//    Byte result[len];
//    char achar[[str length]];
//    memcpy(achar, [[str uppercaseString] cStringUsingEncoding:NSASCIIStringEncoding], 2*[[str uppercaseString] length]);
//    for (int i = 0; i<len; i++) {
//        int pos = i *2;
//        result[i] = (Byte)([GYBleDataManager toByte:achar[pos]] <<   4 | [GYBleDataManager toByte:achar[pos+1]]);
//        //NSLog(@"result[i]:%d",result[i]);
//    }
    Byte *ceshi = (Byte *)data.bytes;
    unsigned short sum = 0;
    for (int i = 0; i<data.length; i++) {
        //NSLog(@"ceshi=============%d",ceshi[i]);
        sum += ceshi[i];
    }
    
//    unsigned short sum = 0;
//        for (int i = 0; i<len; i++) {
//        if (i == 0) {
//            sum = result[0];
//        }else{
//            sum += result[i];
//        }
//    }
    sum += param;
    unsigned short count =~sum;
//    NSLog(@"sum========%@",[NSString stringWithFormat:@"%x",sum]);
//    NSLog(@"count============%@",[NSString stringWithFormat:@"%x",count]);
    Byte low = count & 0XFF;//WORD_HI(count);
    count >>=8; //像右移 8未
//    NSLog(@"height========%@",[NSString stringWithFormat:@"%x",count]);
//    NSLog(@"low========%@",[NSString stringWithFormat:@"%x",low]);
    
    Byte foot[2];
    foot[0] = count;
    foot[1] = low;
    
    NSData *footData = [NSData dataWithBytes:foot length:2];
    
    return footData;
}
+ (Byte)toByte:(char)c {
    Byte b = (Byte)[@"0123456789ABCDEF" rangeOfString:[NSString stringWithFormat:@"%c", c]].location;
    return b;
}
/**
 *    @brief    将二进制数据转化为用字符表示的16进制数
 *
 *    @param     data 二进制数据
 *
 *    @return    字符表示的16进制数 
 */
-(NSString *)HexStringWithData:(NSData *)data{
    Byte *bytes = (Byte *)[data bytes];
    NSString *hexStr=@"";
    for(int i=0;i<[data length];i++) {
        NSString *newHexStr = [NSString stringWithFormat:@"%x",bytes[i]&0xff];///16进制数
        if([newHexStr length]==1){
            hexStr = [NSString stringWithFormat:@"%@0%@",hexStr,newHexStr];
        }
        else{
            hexStr = [NSString stringWithFormat:@"%@%@",hexStr,newHexStr];
        }
    }
    hexStr = [hexStr uppercaseString];
    return hexStr;
}
@end
